#include <sxQSquareFrameLayout.h>

/* Qt Includes */
#include <QGridLayout>

const unsigned int DEFAULT_WIDTH = 400;
const unsigned int DEFAULT_HEIGHT = 400;
const unsigned int VIEWPORT_MINIMUM_WIDTH = 200;
const unsigned int VIEWPORT_MINIMUM_HEIGHT = 200;
const unsigned int DEFAULT_SPLITTER_WIDTH = 4;
const unsigned int VIEWPORT_COUNT = 4;

Sx::QtInterface::QSquareFrameLayout::QSquareFrameLayout(QWidget* parent) : QViewportFrameLayout(parent) {
	QGridLayout* gridLayout = new QGridLayout(this);
	gridLayout->setContentsMargins(0, 0, 0, 0);

	this->hSplitter = new QSplitter(Qt::Horizontal, this);
	this->hSplitter->setChildrenCollapsible(false);
	this->hSplitter->setOpaqueResize(false);
	this->hSplitter->setHandleWidth(DEFAULT_SPLITTER_WIDTH);
	this->hSplitter->resize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	this->layout()->addWidget(this->hSplitter);

	this->vSplitterHigh = new QSplitter(Qt::Vertical, this->hSplitter);
	this->vSplitterHigh->setChildrenCollapsible(false);
	this->vSplitterHigh->setOpaqueResize(false);
	this->vSplitterHigh->setHandleWidth(DEFAULT_SPLITTER_WIDTH);
	this->vSplitterHigh->resize(DEFAULT_WIDTH, DEFAULT_HEIGHT / 2);

	this->vSplitterLow = new QSplitter(Qt::Vertical, this->hSplitter);
	this->vSplitterLow->setChildrenCollapsible(false);
	this->vSplitterLow->setOpaqueResize(false);
	this->vSplitterLow->setHandleWidth(DEFAULT_SPLITTER_WIDTH);
	this->vSplitterLow->resize(DEFAULT_WIDTH, DEFAULT_HEIGHT / 2);
}

Sx::QtInterface::QSquareFrameLayout::~QSquareFrameLayout() {
	/* The viewportFrames array pointers are managed by Qt */
}
	
unsigned int Sx::QtInterface::QSquareFrameLayout::getRequiredViewportCount() const {
	return VIEWPORT_COUNT;
}

bool Sx::QtInterface::QSquareFrameLayout::setViewportFrames(const Util::ArrayList<QViewportFrame*>& viewports) {
	if ( viewports.size() != VIEWPORT_COUNT ) {
		std::cerr << "[QSquareFrameLayout:setViewportFrames] Error: Square viewport layout only accepts: " << VIEWPORT_COUNT << " viewport frames." << std::endl;
		return false;
	}

	this->viewportFrames = viewports;
	
	for ( unsigned int i = 0; i < VIEWPORT_COUNT; i++ ) {
		if ( viewports[i] == nullptr ) {
			std::cerr << "[QSquareFrameLayout:setViewportFrames] Error: Cannot add nullptr viewport frame to this viewport." << std::endl;
			return false;
		}

		if ( i < 2 ) this->vSplitterHigh->addWidget(viewports[i]);
		else this->vSplitterLow->addWidget(viewports[i]);

		this->connect(viewports[i], SIGNAL(gainsFocus(QViewportFrame*)), this, SLOT(onFocusedViewportChange(QViewportFrame*)));
	}

	return true;
}
